package util;
/**
 * Copyright (C) 2008 Universidade Federal de Campina Grande
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *         http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import org.codehaus.plexus.util.StringUtils;

import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

/**
 * @author thiagoepdc
 * @author Jonhnny Weslley - jonhnny@lsd.ufcg.edu.br
 *
 */
@SuppressWarnings("unchecked")
public class RemoteService<E extends RemoteService<E>> {

	protected String userName;
	protected String hostName;
	protected String identityFile;

	public E connectMe() {
		return connect(System.getProperty("user.name"));
	}

	public E connect(String username) {
		this.userName = username;
		return (E) this;
	}

	public E at(String hostname) {
		this.hostName = hostname;
		return (E) this;
	}

	public E usingIdentificationFrom(String identityfile) {
		this.identityFile = identityfile;
		return (E) this;
	}

	/**
	 * @return
	 * @throws JSchException
	 */
	protected Session createSession() throws JSchException {

		if (StringUtils.isEmpty(userName)) {
			connectMe();
		}

		if (StringUtils.isEmpty(hostName)) {
			at("localhost");
		}

		if (StringUtils.isEmpty(identityFile)) {
			usingIdentificationFrom(System.getProperty("user.home") + "/.ssh/id_dsa");
		}

		JSch jsch = new JSch();
		Session session = jsch.getSession(userName, hostName, 22);

		jsch.addIdentity(identityFile);

		java.util.Properties config = new java.util.Properties();
		config.put("StrictHostKeyChecking", "no");

		session.setConfig(config);
		session.setUserInfo(new DefaultUserInfo(null));

		return session;
	}

}
